import logging
import sys

from loguru import logger


class InterceptHandler(logging.Handler):
    def emit(self, record):
        # 获取 Loguru 级别
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        # 找到日志记录的调用者
        frame, depth = logging.currentframe(), 2
        while frame and depth > 0:
            frame = frame.f_back
            depth -= 1

        logger.opt(depth=6, exception=record.exc_info).log(level, record.getMessage())


def setup_logging():
    logger.bind(request_id="")
    # 移除所有标准日志处理器
    logging.root.handlers = []
    logging.root.setLevel(logging.INFO)

    # 添加拦截处理器
    logging.root.addHandler(InterceptHandler())
    log_formatter = '{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {extra} | {name}:{function}:{line} - {message}'
    # 配置 Loguru 的接收器
    logger.remove()  # 移除默认处理器
    logger.add(sys.stdout, format=log_formatter, level="INFO")
    logger.add("/data/ocrapp/logs/app.{time:YYYY-MM-DD}.log",
               rotation="00:00",  # 每天生成一个新文件
               retention="720 days",
               # compression="zip",
               level="INFO",
               format=log_formatter)
